<template>
	<view>
		<view class="article-title">{{title}}</view>
		<view class="article-content">{{content}}</view>
		<view class="article-comment">
			<view class="article-comment-item" v-for="(item,index) in commentList" :key="index">
				<view class="user-info">
					<image class="avatar" :src="item.userInfo.avatar || '../../static/logo.png'" mode="widthFix"></image>
					<text class="username">{{item.userInfo.username || '佚名'}}</text>
				</view>
				<view class="comment-content">
					<text v-if="item.comment_type === 1" class="comment-at">@{{item.replyUserInfo.username + ' '}}</text>{{item.comment_content}}
				</view>
				<view class="comment-action">
					<view class="action" @click="commentToReply(item._id,item.user_id,item.userInfo.username)">回复</view>
				</view>
			</view>
			<uni-load-more :status="commentStatus"></uni-load-more>
		</view>
		<view class="article-comment-zan" @click="zan">{{zaned ? likeCount + '赞' : '点赞'}}</view>
		<view class="article-comment-add" @click="commentToArticle">评论</view>
		<view class="article-comment-input">
			<input v-if="hasLogin" type="text" v-model.trim="commentContent" :placeholder="commentType === 0 ? '留下你的评论' : `@${replyUserName}`"
			 @confirm="comment" />
			<view v-else class="not-login" @click="toLogin">请登录后再评论</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	export default {
		data() {
			return {
				articleId: '',
				title: '',
				content: '',
				zaned: '',
				likeCount: '',
				loading: false,
				commentList: [],
				commentCurrentPage: 1,
				commentPageSize: 20,
				commentLoading: false,
				commentStatus: 'more',
				commentType: 0,
				commentContent: '',
				replyCommentId: '',
				replyUserId: '',
				replyUserName: ''
			}
		},
		computed: {
			...mapState(['hasLogin'])
		},
		watch: {
			hasLogin() {
				this.loadArticle()
			}
		},
		onLoad(options) {
			this.articleId = options.id
			if (!this.articleId) {
				uni.reLaunch({
					url: '/pages/index/index'
				})
				return
			}
			this.loadArticle()
			this.loadComment()
		},
		onReachBottom() {
			this.loadComment()
		},
		methods: {
			loadArticle() {
				this.loading = true
				uni.showLoading({
					title: '加载中...'
				})
				const db = this.$db,
					dbCmd = db.command,
					$ = dbCmd.aggregate
				const query = this.hasLogin ? db.collection('opendb-news-articles').aggregate()
					.match({
						_id: this.articleId,
						publish_date: dbCmd.gt(Date.now() - 365 * 24 * 3600000)
					})
					.lookup({
						from: 'opendb-news-favorite',
						let: {
							articleId: '$_id'
						},
						pipeline: $.pipeline().match(dbCmd.and([{
								user_id: db.env.uid
							},
							dbCmd.expr(
								$.eq(
									['$article_id', '$$articleId']
								)
							)
						])).done(),
						as: 'zanLog'
					})
					.addFields({
						zaned: $.size('$zanLog')
					})
					.end() : db.collection('opendb-news-articles')
					.where({
						_id: this.articleId,
						publish_date: dbCmd.gt(Date.now() - 365 * 24 * 3600000)
					}).get()
				query.then((res) => {
					if (res.result.code) {
						uni.showModal({
							content: res.result.message,
							showCancel: false
						})
						return
					}
					const data = res.result.data
					if (data.length === 1) {
						this.title = data[0].title
						this.content = data[0].content
						this.zaned = data[0].zaned > 0
						this.likeCount = data[0].like_count || 0
					} else {
						uni.showModal({
							content: '文章不存在',
							showCancel: false
						})
					}
				}).catch((err) => {
					uni.showModal({
						content: '获取文章详情失败',
						showCancel: false
					})
				}).finally(() => {
					uni.hideLoading()
					this.loading = false
				})
			},
			loadComment(reload) {
				if (reload) {
					this.commentCurrentPage = 1
				}
				this.commentLoading = true
				this.commentStatus = 'loading'
				const db = this.$db,
					dbCmd = db.command,
					$ = dbCmd.aggregate
				db.action('get-comment')
					.collection('opendb-news-comments')
					.aggregate()
					.match({
						article_id: this.articleId
					})
					.sort({
						'comment_date': -1
					})
					.skip((this.commentCurrentPage - 1) * this.commentPageSize)
					.limit(this.commentPageSize)
					.lookup({
						from: 'uni-id-users',
						let: {
							userId: '$user_id',
							replyUserId: '$reply_user_id'
						},
						pipeline: $.pipeline().match(
							dbCmd.expr($.or([
								$.eq(['$_id', '$$userId']),
								$.eq(['$_id', '$$replyUserId'])
							]))
						).project({
							username: true,
							avatar: true
						}).done(),
						as: 'userList'
					})
					.end()
					.then((res) => {
						console.log(res)
						const tempList = res.result.data
						if (tempList.length === this.commentPageSize) {
							this.commentStatus = 'more'
						} else {
							this.commentStatus = 'noMore'
						}
						if (reload) {
							this.commentList = tempList
						} else {
							this.commentList = this.commentList.concat(tempList)
						}
						if (tempList.length) {
							this.commentCurrentPage++
						}
					})
					.catch((err) => {
						uni.showModal({
							content: '获取评论列表失败',
							showCancel: false
						})
					})
					.finally(() => {
						this.commentLoading = false
					})
			},
			toLogin() {
				uni.navigateTo({
					url: '/pages/login/login'
				})
			},
			commentToArticle() {
				this.commentType = 0
			},
			commentToReply(replyCommentId, replyUserId, replyUserName) {
				this.commentType = 1
				this.replyCommentId = replyCommentId
				this.replyUserId = replyUserId
				this.replyUserName = replyUserName
			},
			comment(e) {
				if (!this.commentContent) {
					uni.showModal({
						content: '内容不能为空',
						showCancel: false
					})
					return
				}
				if (this.commentSending) {
					uni.showToast({
						title: '发言过快',
						icon: 'none'
					})
					return
				}
				this.commentSending = true
				const commentContent = this.commentContent
				const db = this.$db,
					dbCmd = db.command
				const data = {
					article_id: this.articleId,
					comment_content: commentContent,
					comment_type: this.commentType,
				}
				if (this.commentType === 1) {
					data.reply_user_id = this.replyUserId
					data.reply_comment_id = this.replyCommentId
				}
				db.action('add-comment')
					.collection('opendb-news-comments')
					.add(data).then((res) => {
						if (res.result.id) {
							this.commentContent = ''
							this.loadComment(true)
						} else {
							uni.showModal({
								content: res.result.message,
								showCancel: false
							})
						}
					}).catch((err) => {
						uni.showModal({
							content: '评论发送失败，请稍后再试',
							showCancel: false
						})
					}).finally(() => {
						this.commentSending = false
					})
			},
			zan() {
				if (!this.hasLogin) {
					uni.showModal({
						content: '请先登录',
						showCancel: false,
						success() {
							uni.navigateTo({
								url: '/pages/login/login'
							})
						}
					})
					return
				}
				if (this.zanLoading) {
					uni.showToast({
						title: '操作过快',
						icon: 'none'
					})
					return
				}
				this.zanLoading = true
				const db = this.$db,
					dbCmd = db.command

				if (this.zaned) {
					db.action('delete-favorite')
						.collection('opendb-news-favorite')
						.where({
							article_id: this.articleId,
							user_id: db.env.uid
						}).remove().then((res) => {
							this.zaned = false
							this.likeCount -= 1
						}).catch((err) => {
							uni.showModal({
								content: '取消点赞失败，请稍后再试',
								showCancel: false
							})
						}).finally(() => {
							this.zanLoading = false
						})
					return
				}
				db.action('add-favorite')
					.collection('opendb-news-favorite')
					.add({
						article_id: this.articleId,
						user_id: db.env.uid
					}).then((res) => {
						this.zaned = true
						this.likeCount += 1
					}).catch((err) => {
						uni.showModal({
							content: '点赞失败，请稍后再试',
							showCancel: false
						})
					}).finally(() => {
						this.zanLoading = false
					})
			}
		}
	}
</script>

<style>

</style>
